package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/*
 * Rest模式
 * */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("login")
    public R<Employee> Login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.将页面提交的密码password进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes(StandardCharsets.UTF_8));
        //2.根据页面提交的用户名username和密码password查询数据库
        Map<String, String> map = new HashMap<>();
        map.put("username", employee.getUsername());
        map.put("password", password);
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(map);
        Employee employeeOne = employeeService.getOne(queryWrapper);
        //3.如果没有查询到,则返回登录失败结果
        if (employeeOne == null) {
            return R.error("用户名或密码错误!!!");
        }
        //4.查看员工状态,如果为已禁用状态.则返回员工已禁用结果
        if (employeeOne.getStatus() == 0) {
            return R.error("账号已禁用");
        }
        //5.登录成功,则将员工id存入Session并返回登录成功结果
        log.info("登录成功,员工id:{}", employeeOne.getId().toString());
        request.getSession().setAttribute("employee", employeeOne.getId());
        return R.success(employeeOne);
    }

    //员工退出
    @PostMapping("logout")
    public R<String> Logout(HttpServletRequest request) {
        //清理Session中保存的当前登录的员工id
        request.getSession().removeAttribute("employee");
        log.info("退出成功");
        return R.success("退出成功");
    }

    //新增员工
    @PostMapping
    public R<String> Save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工,员工信息:{}", employee.toString());

        //设置初始密码为123456,需要进行md5加密处理
        String password = DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8));
        employee.setPassword(password);

        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //获取当前登录用户的id
        Long employeeId = (Long) request.getSession().getAttribute("employee");

        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);*/

        //添加员工
        try {
            employeeService.save(employee);
            log.info("添加成功");
            return R.success("添加成功");
        } catch (Exception e) {
            return R.error("账号已存在,请重新填写账号");
        }
    }

    //员工信息分页查询
    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //创建分页构造器
        Page<Employee> pageInfo = new Page(page, pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加模糊查询条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行分页查询
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    //    根据id修改员工信息
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
      /*  employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        employee.setUpdateTime(LocalDateTime.now());*/
        try {
            employeeService.updateById(employee);
            employeeService.list();
            return R.success("员工信息修改成功");
        } catch (Exception e) {
            return R.error("员工信息修改失败");
        }
    }

    //根据员工Id查询员工信息
    @GetMapping("{id}")
    public R<Employee> getById(@PathVariable("id") Long id) {
        Employee employeeOne = employeeService.getById(id);
        if (employeeOne != null) {
            return R.success(employeeOne);
        } else {
            return R.error("网络繁忙,请稍后再试");
        }
    }
}

